const express = require("express");
const User = require("../model/user");
const Login = require("../middleware/login");

// 创建登陆应用
const loginApp = express();
// loginApp.use(express.static('public'));
// loginApp.use(bodParser.urlencoded({extended:false}))
// 登陆
loginApp.post("/", [Login.login],(req, res, next) => {
  if (req.token) {
    return res.status(200).json({
      code: 200,
      message: '登录成功',
      token: req.token,
      data: Object.assign({ token: "admin-token" })
    })
  } else {
    res.json({
      code: 400,
      data: '登录失败，请检查用户名和密码是否正确'
    })
  }
  
});
loginApp.get('/info', (req, res) => {
  console.log(req.query);
  if (req.query.token == 'admin-token') {
    res.json({
      code: 200,
      data: {
        avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        introduction: "I am a super administrator",
        name: "Super Admin",
        roles: ["admin"]
      }
    })
  } else {
    res.json({
      code: 400,
      data: '登录失败'
    })
  }
})
// 用户列表
loginApp.get("/userlist", [Login.UserList], (req, res, next) => {
  res.json({
    userList: req.userList,
    total: req.total
  });
});
// 删除用户
loginApp.post("/delUser", [Login.delUser], (req, res) => {
  if (req.affectedRows > 0) {
    res.json({
      code: 200,
      msg: "删除成功",
    });
  } else {
    res.json({
      code: 404,
      msg: "删除失败",
    });
  }
});
// 用户添加
loginApp.post("/userAdd", [Login.userAdd], (req, res) => {
  if (req.insertId) {
    res.json({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.json({
      code: 404,
      msg: "添加失败",
    });
  }
});
// 编辑用户信息
loginApp.post("/editUser", [Login.editUser], (req, res) => {
  if (req.affectedRows > 0) {
    res.json({
      code: 200,
      msg: "用户编辑成功",
    });
  } else {
    res.json({
      code: 404,
      msg: "用户编辑失败",
    });
  }
});
module.exports = loginApp;
